// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SnapObjects.Data
{
    internal abstract class SqlFunctionStatementGenerator : SqlStatementGenerator
    {
        public SqlFunctionStatementGenerator(
            ISqlStatementFactory factory,
            ISqlGenerationHelper helper,
            ITypeMapper typeMapper) : base(factory, helper, typeMapper)
        {
        }

        public override SqlSyntaxDescription Create(SqlStatement statement)
        {
            var function = (SqlFunctionStatement)statement;

            var tokens = this.SpliceStatement(function);

            var builder = new StringBuilder();

            foreach (var token in tokens)
            {
                if (token.Type == SqlTokenType.Identifier)
                {
                    builder.Append(_helper.DelimitIdentifier(token.Text));
                }
                else
                {
                    builder.Append(token.Text);
                }
            }

            var functionName = builder.ToString();

            builder.Clear();

            this.CreateSelectColumns(builder, statement, functionName);

            this.CreateFrom(builder, statement, functionName);

            var parameters = function.Parameters.ToDictionary(
                m => m.Key, m => _helper.GenerateParameterName(m.Key));

            return new SqlSyntaxDescription(builder.ToString(), parameters, true);
        }

        protected override IReadOnlyList<SqlToken> SpliceStatement(SqlStatement statement)
        {
            var function = (SqlFunctionStatement)statement;

            return function.Function.ToList();
        }

        protected virtual void CreateSelectColumns(
            StringBuilder sqlBuilder, SqlStatement statement, string functionName)
        { 
            var function = (SqlFunctionStatement)statement;

            sqlBuilder.Append(new SqlKeywordToken(SqlKeywords.SELECT));

            sqlBuilder.Append(SqlWhitespaceToken.Whitespace);

            if (function.ReturnType == FunctionReturnType.Scalar)
            {
                sqlBuilder.Append(functionName);

                this.CreateParameters(sqlBuilder, statement);
            }
            else
            {
                sqlBuilder.Append("*");
            }
        }

        protected virtual void CreateFrom(
            StringBuilder sqlBuilder, SqlStatement statement, string functionName)
        {
            var function = (SqlFunctionStatement)statement;

            if (function.ReturnType != FunctionReturnType.Scalar)
            {
                sqlBuilder.Append(SqlWhitespaceToken.Whitespace);
                sqlBuilder.Append(new SqlKeywordToken(SqlKeywords.FROM));
                sqlBuilder.Append(SqlWhitespaceToken.Whitespace);
                sqlBuilder.Append(functionName);

                this.CreateParameters(sqlBuilder, statement);
            }
        }

        protected virtual void CreateParameters(StringBuilder sqlBuilder, SqlStatement statement)
        {
            var function = (SqlFunctionStatement)statement;

            var parameters = function.Parameters;

            sqlBuilder.Append(SqlCharacters.OpenParentheses);

            var isFirstAppendParameter = true;

            foreach (var parameter in parameters)
            {
                if (!isFirstAppendParameter)
                {
                    sqlBuilder.Append(SqlCharacters.Comma);
                }

                var parameterName = _helper.GenerateParameterName(parameter.Key);

                sqlBuilder.Append(parameterName);

                isFirstAppendParameter = false;
            }

            sqlBuilder.Append(SqlCharacters.CloseParentheses);
        }
    }
}
